﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Dev.Control;
using SfcorpDLL.biz;
using GT.ORM;
using Billing;
using Billing.ety;
using GT.ReportDLL.Biz;
using GT.ReportDLL.ety;
using System.Collections;
using DevExpress.XtraBars;
using DevExpress.XtraTreeList.Nodes;
using SfcorpDLL.ety;

namespace Sfcorp.form
{
    public partial class frmAccount : BaseFormDev
    {
        bizAccount bzAccount;
        bizAgyBns bzAgyBns;

        public frmAccount()
        {
            InitializeComponent();
        }
        private void frmAccount_Load(object sender, EventArgs e)
        {
            bzAccount = new bizAccount(global.basSysPara);
            bzAgyBns = new bizAgyBns(global.basSysPara);
            
            if (DateTime.Now.Day >= 20)//如果大于20号，日期默认为当月
            {
                deFromDate.DateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                deEndDate.DateTime = (new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)).AddMonths(1).AddSeconds(-1);
            }
            else //小于20号，日期默认为上月
            {
                deFromDate.DateTime = (new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)).AddMonths(-1);
                deEndDate.DateTime = (new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)).AddSeconds(-1);
            }
            dtAccountMM.DateTime = deFromDate.DateTime;
            //明细表
            ggcChrgDtl.GridView = this.gridView1;
            ggcChrgDtl.GridView.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.Click;
            string sMapingCols = "CUSTOMER_NAME,ITEM_DESC,IO_FLAG_DESC,CASH_FLAG_DESC,UNIT_DESC,PRICE,QTY ,AMOUNT,BILL_NO,INVOICE_NO,CHRG_DESC2,CHRG_DESC3,CHRG_DESC4,CHRG_DESC5,CHRG_FLT20,CHRG_DESC22  ,CHRG_DESC23,CHRG_FLT24,CHRG_DESC26,CHRG_DESC24,CHRG_DESC25,CHRG_DESC26";
            string sMapingHeaderTxt = "客户         ,费目     ,收支        ,交现金        ,单位     ,单价 ,数量,合计  ,计费编号        ,帐单编号,货代公司  ,进出口    ,结算方式  ,作业方式  ,业务单号  ,合作方       ,办单人     ,箱号      ,货物名称,提单号1,提单号2,箱号";
            ggcChrgDtl.ColumnsMappingCreate(sMapingCols.Replace(" ", ""), sMapingHeaderTxt.Replace(" ", ""));
            this.winUtil.LoadGridLayout(ggcChrgDtl);
            ggcChrgDtl.GridView.OptionsView.ShowGroupPanel = true;
            //汇总表
            ggcAccount.GridView = this.gridView2;
            ggcAccount.GridView.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.Click;
            //this.winUtil.LoadGridLayout(ggcAccount);
            ggcAccount.GridView.OptionsView.ShowGroupPanel = true;

            deFromDate.DateTimeChanged += new EventHandler(deFromDate_DateTimeChanged);
            deEndDate.DateTimeChanged += new EventHandler(deEndDate_DateTimeChanged);
            //tvPreAccComp.FocusedNodeChanged += new DevExpress.XtraTreeList.FocusedNodeChangedEventHandler(tvPreAccComp_FocusedNodeChanged);
            tvChrgHdr.FocusedNodeChanged += new DevExpress.XtraTreeList.FocusedNodeChangedEventHandler(tvChrgHdr_FocusedNodeChanged);

            RefreshDate();

            xtraTabPage2.PageVisible = false;
            cTabControl1.SelectedTabPageIndex = 1;
            
        }

        void deEndDate_DateTimeChanged(object sender, EventArgs e)
        {
            RefreshDate();
        }

        void deFromDate_DateTimeChanged(object sender, EventArgs e)
        {
            RefreshDate();
        }

        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RefreshDate();
        }
        public override Dev.Control.etyQuickKey RefreshDate()
        {
            BindTree();
            return base.RefreshDate();
        }

        //建立树
        private void BindTree()
        {
            string tvInvoice = string.Empty;
            DateTime dFormDate = deFromDate.DateTime;
            DateTime dEndDate = deEndDate.DateTime;
            etyChargeDtl eyChrgDtl = new etyChargeDtl();
            eyChrgDtl.PORT_CODE = global.basSysPara.PORT_CODE;
            eyChrgDtl.BILL_MONTH = dtAccountMM.DateTime.ToString("yyyyMM");
            //绑定左上角的未生成账单公司列表
            IList<GT.ORM.etyChargeHdr> custList = bzAccount.GetPreAccComp(dFormDate, dEndDate);
            tvPreAccComp.DataSource = custList;
            //绑定左下角的账单公司列表
            IList<etyChargeHdr> chrgHdrList = bzAccount.GetChargeHdrList(eyChrgDtl);
            tvChrgHdr.DataSource = chrgHdrList; tvChrgHdr.Nodes.Clear();
            System.Collections.Hashtable hashCompNo = new System.Collections.Hashtable();
            foreach (etyChargeHdr chrgHdr in chrgHdrList)
            {
                DevExpress.XtraTreeList.Nodes.TreeListNode compNode;
                if (!hashCompNo.ContainsKey(chrgHdr.CUSTOMER))           //主
                {
                    tvInvoice = string.Format("{0}:{1}", new string[] { chrgHdr.CUSTOMER, chrgHdr.CUSTOMER_NAM });
                    compNode = tvChrgHdr.AppendNode(new object[] { tvInvoice }, null);
                    hashCompNo.Add(chrgHdr.CUSTOMER, compNode);
                    compNode.Tag = chrgHdr;
                }
                else
                {                                                        //子
                    compNode = hashCompNo[chrgHdr.CUSTOMER] as DevExpress.XtraTreeList.Nodes.TreeListNode;
                }
                tvInvoice = string.Format("{0}<{1}>", new string[] {chrgHdr.INVOICE_NO,chrgHdr.STATUS=="A"?"已审批":"未审批" });
                DevExpress.XtraTreeList.Nodes.TreeListNode invNode
                    = tvChrgHdr.AppendNode(new object[] { tvInvoice }, compNode);
                invNode.Tag = chrgHdr;
            }
            tvChrgHdr.FocusedNode = null;
            tvPreAccComp.FocusedNode = null;
        }

        
        private void tvPreAccComp_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            PreAccCompClick();
        }

        //点左上角树
        private void PreAccCompClick()
        {
            TreeListNode Node = tvPreAccComp.FocusedNode;
            if (Node == null)
                return;
            etyChargeHdr chrgHdr = Node.Tag as etyChargeHdr;
            if (chrgHdr == null)
                return;
            string compNo = chrgHdr.CUSTOMER;
            string compName = chrgHdr.CUSTOMER_NAM;

            lbCustomer.Text = compNo;
            lbCustName.Text = compName;
            IList<etyChargeDtl> ilBillResult = bzAccount.GetBillResult(deFromDate.DateTime, deEndDate.DateTime, compNo);
            srcBinding.DataSource = ilBillResult;
            ggcChrgDtl.DataSource = srcBinding;
            ggcChrgDtl.AutoColumnWidth();
            decimal dTotal = 0;
            foreach (etyChargeDtl billResult in ilBillResult)
            {
                decimal dAmount = decimal.Parse(billResult.AMOUNT);
                dTotal += dAmount;
            }
            txtAmount.Text = dTotal.ToString();

            if (tvChrgHdr.FocusedNode != null)
            {
                tvChrgHdr.FocusedNode = null;
                tvChrgHdr.Refresh();
            }
            if (ilBillResult.Count > 0)
            {
                btnSave.Enabled = true;
            }
            else
            {
                btnSave.Enabled = false;
            }
            btnDelete.Enabled = false;
            ggcAccount.DataSource = new DataTable();
            xtraTabPage2.PageVisible = false;
        }

        private void tvChrgHdr_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            LoadAccountDtl(e.Node);
        }
        //点左下角树
        private void LoadAccountDtl(TreeListNode node)
        {
            DataTable dtAccountCross = new DataTable();
            IList<etyChargeDtl> ilChrgDtl = new List<etyChargeDtl>();
            GT.ORM.etyChargeDtl eyAccount = new etyChargeDtl();
            if (node == null)
                return;
            etyChargeHdr chrgHdr = node.Tag as etyChargeHdr;
            if (chrgHdr == null)
                return;
            lbCustomer.Text = chrgHdr.CUSTOMER;
            lbCustName.Text = chrgHdr.CUSTOMER_NAM;
            eyAccount.CUSTOMER = chrgHdr.CUSTOMER;
            eyAccount.BILL_MONTH = dtAccountMM.DateTime.ToString("yyyyMM");
            eyAccount.INVOICE_NO = chrgHdr.INVOICE_NO;

            #region ***数据填充
            if (node.ParentNode == null)       //整间公司查看
            {
                eyAccount.INVOICE_NO = string.Empty;
                ilChrgDtl = bzAccount.GetCompCharge(eyAccount);     //**明细数据
                barCheck.Enabled = false;
                barUnCheck.Enabled = false;
            }
            else
            {
                ilChrgDtl = bzAccount.GetChargeDtl(eyAccount);      //**明细数据
                //审核控制
                barCheck.Enabled = chrgHdr.STATUS == "N" ? true : false;
                barUnCheck.Enabled = !barCheck.Enabled;
            }
            //明细
            txtAmount.Text = TT.Common.dataProcessor.ListSumAmount<etyChargeDtl>(ilChrgDtl, "AMOUNT").ToString();
            srcBinding.DataSource = ilChrgDtl;
            ggcChrgDtl.DataSource = srcBinding;
            ggcChrgDtl.AutoColumnWidth();
            //汇总
            dtAccountCross = bzAccount.GetCompChargeCross(eyAccount);       //汇总数据
            scrGrid2.DataSource = dtAccountCross;
            ggcAccount.DataSource = scrGrid2;
            string gridHead = "[PORT_NAM;港口],[CONTRACT_DATE;日期],[CONTRACT_NO;单号],[CLIENT_NAM;办单人],[CLIENT_CONTACT;联系方式],[WORK_WAY_NAM;作业方式],[SEA_BILL_NO;提单1],[AGENT_BILL_NO;提单2],[PORT_CONTRACT;码头单号],[CNTR;柜号],[CNTR_TYPE;尺寸类型],[ITEM_DESC;费用描述],[AMOUNT;总金额]";
            ggcAccount.ColumnsTranslate(gridHead);
            ggcAccount.AutoColumnWidth();
            ggcAccount.ColumnsTranslate(gridHead);
            #endregion

            if (tvPreAccComp.FocusedNode != null)
            {
                tvPreAccComp.FocusedNode = null;
                tvPreAccComp.Refresh();
            }
            btnSave.Enabled = false;
            btnDelete.Enabled = true;
            if (!xtraTabPage2.PageVisible)
            {
                xtraTabPage2.PageVisible = true;
                cTabControl1.SelectedTabPageIndex = 0;
            }
        }

        //保存帐单
        private void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SaveDate();
        }
        public override etyQuickKey SaveDate()
        {
            string billMonth = dtAccountMM.DateTime.ToString("yyyyMM");
            IList<etyChargeDtl> chrgDtl = srcBinding.DataSource as IList<etyChargeDtl>;
            if (chrgDtl == null || chrgDtl.Count < 1)
            {
                TT.HelpInfo.MsgBox.ShowSuccessBox("没有可保存的计费记录");
                return base.SaveDate();
            }
            if (TT.HelpInfo.MsgBox.ShowQuestionBox(string.Format("是否把帐单保存到{0}？", new string[] { dtAccountMM.DateTime.ToString("yyyy年MM月") })) == false)
                return base.SaveDate();
            foreach (etyChargeDtl ey in chrgDtl)    //月份赋值
                ey.BILL_MONTH = billMonth;
            bool isSave = bzAccount.SaveChargeHdrDtl(chrgDtl);
            if (isSave)
            {
                btnSave.Enabled = false;
                btnDelete.Enabled = false;
                RefreshDate();
            }
            TT.HelpInfo.MsgBox.ShowSuccessFailBox(isSave);

            ggcChrgDtl.AutoColumnWidth();

            return base.SaveDate();
        }

        private void tvChrgHdr_GetSelectImage(object sender, DevExpress.XtraTreeList.GetSelectImageEventArgs e)
        {
            if (e.Node.ParentNode == null) e.NodeImageIndex = 0;
            else e.NodeImageIndex = (e.FocusedNode) ? 2 : 1;
        }
        private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DeleteDate();
        }
        public override etyQuickKey DeleteDate()
        {
            if (tvChrgHdr.FocusedNode == null)
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("请先选择一个账单号来删除");
                return base.DeleteDate();
            }
            etyChargeHdr chrgHdr = tvChrgHdr.FocusedNode.Tag as etyChargeHdr;
            if (chrgHdr == null)
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("请先选择一个账单号来删除");
                return base.DeleteDate();
            }
            if (!TT.HelpInfo.MsgBox.ShowQuestionBox("是否删除账单："+chrgHdr.INVOICE_NO+"？"))
                return base.DeleteDate();
            if (bzAccount.DeleteChargeHdr(chrgHdr))
            {
                TT.HelpInfo.MsgBox.ShowSuccessBox("删除账单成功");
                RefreshDate();
            }
            else
                TT.HelpInfo.MsgBox.ShowSuccessBox("删除账单失败");
            return base.DeleteDate();
        }

        private void btnExit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            F12();
        }

        private void btnSearch_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            F7();
        }

        private void barPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            F11();
        }

        //打印
        public override etyQuickKey F11()
        {
            try { splashScreenManager1.ShowWaitForm(); }
            catch { };
            //if (tabCntr.SelectedIndex == 0) return "";
            etyChargeHdr chrgHdr = tvChrgHdr.FocusedNode.Tag as etyChargeHdr;
            if (chrgHdr == null)
                return base.F11();
            try
            {
                bizRptMainForm bzRptMain;
                bzRptMain = new bizRptMainForm(global.basSysPara.SqlHelp, global.basSysPara.PORT_CODE);
                DataSet dsRptParam = new DataSet();
                etyRptDtl eyRpt = new etyRptDtl();
                eyRpt.RPT_NAME = "货代给客户账单";
                eyRpt = bzRptMain.GetRptDtl(eyRpt)[0];

                dsRptParam = TT.Common.xmlProcessor.GetXmlDataSetFromString(eyRpt.RPT_DTL);

                if (dsRptParam != null)
                {
                    Hashtable htParam = new Hashtable();
                    htParam.Add("CUSTOMER", chrgHdr.CUSTOMER);
                    htParam.Add("BILL_MONTH",dtAccountMM.DateTime.ToString("yyyyMM"));
                    bzRptMain.PrintXLS(dsRptParam, htParam);
                }
                try { splashScreenManager1.CloseWaitForm(); }
                catch { }
            }
            catch (Exception ex)
            {
                try { splashScreenManager1.CloseWaitForm(); }
                catch { }
                MessageBox.Show(ex.ToString());

            }
            return base.F11();
        }

        private void bbtRefresh_Click(object sender, EventArgs e)
        {
            RefreshDate();
        }

        private void barChargeHdrCheck_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            BarLargeButtonItem btn = sender as BarLargeButtonItem;
            
            if (tvChrgHdr.FocusedNode == null)
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("请先选择一个账单号。");
                return;
            }
            etyChargeHdr chrgHdr = tvChrgHdr.FocusedNode.Tag as etyChargeHdr;
            chrgHdr.STATUS = e.Item.Tag.ToString();
            if (chrgHdr == null)
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("请先选择一个账单号。");
                return;
            }
            if (!TT.HelpInfo.MsgBox.ShowQuestionBox("是否审核帐单：" + chrgHdr.INVOICE_NO + "？"))
                return;
            if (bzAccount.UpdateChargeHdr(chrgHdr))
            {
                TT.HelpInfo.MsgBox.ShowSuccessBox("账单审核成功!");
                RefreshDate();
            }
            else
                TT.HelpInfo.MsgBox.ShowWarnBox("账单审核失败!");
            return;
        }

        private void barDeleBill_ItemClick(object sender, ItemClickEventArgs e)
        {
            IList<etyChargeDtl> ilBillResult = ggcChrgDtl.SelectRows<etyChargeDtl>();
            if (ilBillResult.Count > 0)
            {
                if (!string.IsNullOrEmpty(ilBillResult[0].INVOICE_NO))
                {
                    TT.HelpInfo.MsgBox.ShowWarnBox("删除之数据有误。");
                    return;
                }
                bool succ = bzAgyBns.Billing_Del_ChargeDtl(ilBillResult);
                TT.HelpInfo.MsgBox.ShowSuccessFailBox(succ);
                if (succ)
                {
                    PreAccCompClick();
                }
            }
            else
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("请选择待删除的计费数据。");
            }
        }

        private void ggcChrgDtl_DoubleClick(object sender, EventArgs e)
        {
            etyFrtAgyBns ey = srcBinding.Current as etyFrtAgyBns;
            if (ey == null)
                return;
            try { splashScreenManager1.ShowWaitForm(); }
            catch { }
            MainForm mainForm = this.MdiParent as MainForm;
            DevExpress.XtraBars.Docking2010.Views.BaseDocument document = null;
            Sfcorp.form.frmAgyBns frmBns;
            if (mainForm.Documents.TryGetValue("Bns", out document))
            {
                frmBns = document.Form as Sfcorp.form.frmAgyBns;
                frmBns.Close();
            }
            frmBns = new Sfcorp.form.frmAgyBns();
            frmBns.ContractNo = ey.CONTRACT_NO;
            frmBns.MOD_ID = "barBns";
            frmBns.MdiParent = this.MdiParent;
            frmBns.Show();
            try { splashScreenManager1.CloseWaitForm(); }
            catch { }
        }


    }
}
